﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;

namespace DynCMS.NET.Infrastructure.IOC.Autofac
{
    internal class IOCProvider : IIOCProvider
    {
        public void Initialize()
        {
            _container = BuildContainer();
        }

        private ContainerBuilder _builder;
        private IContainer _container;

        internal IContainer Container
        {
            get
            {
                _container = _container ?? BuildContainer();
                return _container;
            }
        }

        private ContainerBuilder Builder
        {
            get
            {
                _builder = _builder ?? new ContainerBuilder();
                return _builder;
            }
        }

        /// <summary>
        /// Resolves instance of Type
        /// </summary>
        /// <typeparam name="Type">Type to resolve instance</typeparam>
        /// <returns>Instance of type</returns>
        public Type Resolve<Type>()
        {
            return this.Container.Resolve<Type>();
        }

        public void Register<IContract, IImplementation>()
            where IImplementation : IContract
            where IContract : class
        {
            this.Builder.RegisterType<IImplementation>().As<IContract>();
            _container = this.Builder.Build();
        }

        private IContainer BuildContainer()
        {
            //var assembly = System.Reflection.Assembly.LoadFrom("DynCMS.NET.DataAccess.dll");

            //var classes = assembly.GetTypes().Where(t => t.IsClass);
            //IOCProvider.Builder.RegisterAssemblyTypes(assembly);
            //IEnumerable<Type> pagerepos = classes.Where(c => c.IsAssignableTo<Core.Interfaces.IDataRepository<Core.Entities.Page>>());
            //foreach (Type impl in pagerepos)
            //{
            //    IOCProvider.Builder.RegisterType(impl).As<Core.Interfaces.IDataRepository<Core.Entities.Page>>();
            //}
            return Builder.Build();
        }

        public Type Resolve<Type>(string name)
        {
            throw new NotImplementedException();
        }

        public void Register<IContract, IImplementation>(string name)
            where IContract : class
            where IImplementation : IContract
        {
            throw new NotImplementedException();
        }

        public void RegisterAllFromAssemblyContaining<Type>()
        {
            throw new NotImplementedException();
        }
    }
}